<template>
  <ContentWrap>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="160px"
      v-loading="formLoading"
      :inline="true"
      class="demo-form-inline"
    >
      <el-row :gutter="20">
        <el-col :span="22">
          <div ref="containerRef" class="scroll-container">
            <el-card :class="[prefixCls, 'mb-15px']" shadow="never" id="target1">
              <template #header>
                <div class="box-card">
                  <span style="font-weight: 700; font-size: 16px;">基本信息</span>
                  <el-checkbox v-model="formData.hasCreate" label="创建账户" style="float: right" border />
                </div>
              </template>
              <el-alert
                title="注：请让您的客户关注货主小程序，以便能使用货主小程序！联系电话即为登录账号，默认密码tslbdp@123456。"
                type="warning"
                show-icon
                :closable="false"
                style="margin-bottom: 15px"
              />
              <el-row>
                <el-col :span="12">
                  <el-form-item label="单位全称" prop="customerName">
                    <el-input
                      v-model="formData.customerName"
                      placeholder="请输入客户名称"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="统一社会信用代码" prop="customerUscc">
                    <el-input v-model="formData.customerUscc" placeholder="请输入统一社会信用代码" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="法人" prop="legalPerson">
                    <el-input
                      v-model="formData.legalPerson"
                      placeholder="请输入法人名称"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="法人身份证" prop="legalIdCardNo">
                    <el-input v-model="formData.legalIdCardNo" placeholder="请输入法人身份证" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="联系人" prop="contacts">
                    <el-input v-model="formData.contacts" placeholder="请输入联系人" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系电话" prop="contactsPhone">
                    <el-input v-model="formData.contactsPhone" placeholder="请输入联系电话" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="所在城市" prop="contactsAddrOptions">
                    <el-cascader
                      :options="cityOptions"
                      v-model="formData.contactsAddrOptions"
                      @change="handleBaseChange"
                      filterable
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="固定电话" prop="fixedPhone">
                    <el-input
                      v-model="formData.fixedPhone"
                      placeholder="请输入固定电话"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="注册地址" prop="registerAddr">
                    <el-input
                      v-model="formData.registerAddr"
                      placeholder="请输入注册地址"
                      style="width: 350px"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="收件地址" prop="receiveAddr">
                    <el-input
                      v-model="formData.receiveAddr"
                      placeholder="请输入收件地址"
                      style="width: 350px"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="经营范围" prop="busiScope">
                    <el-input v-model="formData.busiScope" type="textarea" :rows="3" style="width: 600px" placeholder="请输入经营范围" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
            <ContentWrap id="target2" title="结算信息">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="结算方式" prop="settlementWays">
                    <el-select
                      v-model="formData.settlementWays"
                      placeholder="请选择结算类型"
                      style="width: 100px"
                    >
                      <el-option
                        v-for="dict in getIntDictOptions(DICT_TYPE.SETTLEMENT_WAYS)"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                    <el-input
                      v-model="formData.settlementDays"
                      placeholder="请输入天数"
                      style="width: 120px"
                      v-if="formData.settlementWays == 2"
                    >
                      <template #append>天</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结算类型" prop="settlementType">
                    <el-select
                      v-model="formData.settlementType"
                      placeholder="请选择结算类型"
                      style="width: 200px"
                    >
                      <el-option
                        v-for="dict in getIntDictOptions(DICT_TYPE.SETTLEMENT_TYPE)"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="付款方式" prop="paymentMethod">
                    <el-select
                      v-model="formData.paymentMethod"
                      placeholder="请选择付款方式"
                      style="width: 200px"
                    >
                      <el-option
                        v-for="dict in getIntDictOptions(DICT_TYPE.PAYMENT_METHOD)"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="回单类型" prop="receiptType">
                    <el-select
                      v-model="formData.receiptType"
                      placeholder="请选择回单类型"
                      style="width: 200px"
                    >
                      <el-option
                        v-for="dict in getIntDictOptions(DICT_TYPE.RECEIPT_TYPE)"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </ContentWrap>
            <el-card :class="[prefixCls, 'mb-15px']" shadow="never" id="target5">
              <template #header>
                <div class="box-card">
                  <span style="font-weight: 700; font-size: 16px;">银行账户</span>
                  <el-button type="primary" @click="openBank" style="float: right"
                  >新增
                  </el-button>
                </div>
              </template>
              <el-table v-loading="loading" :data="bankList">
                <el-table-column label="收款人" align="center" prop="payeeName" />
                <el-table-column
                  label="开户行编码"
                  align="center"
                  prop="bankCode"
                />
                <el-table-column label="开户行" align="center" prop="bankName" />
                <el-table-column label="开户支行" align="center" prop="bankBranchName" />
                <el-table-column label="开户名" align="center" prop="bankAccountName" />
                <el-table-column label="银行账号" align="center" prop="bankAccountNo" />
                <el-table-column label="默认" align="center" prop="hasDefault">
                  <template #default="scope">
                    <el-switch
                      inline-prompt
                      active-text="默认"
                      active-value="1"
                      active-color="#2fa1f1"
                      inactive-text="停用"
                      inactive-value="0"
                      inactive-color="#9c9c9c"
                      v-model="scope.row.hasDefault"
                      @click="handleDefChange(scope.row)"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template #default="scope">
                    <el-button link type="primary" @click="editBank(scope)">编辑</el-button>
                    <el-button link type="danger" @click="handleBankDelete('0', scope)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
            <el-card :class="[prefixCls, 'mb-15px']" shadow="never" id="target3">
              <template #header>
                <div class="box-card">
                  <span style="font-weight: 700; font-size: 16px;">发货人(非必填项)</span>
                  <el-button type="primary" @click="openContacts('0')" style="float: right"
                  >新增
                  </el-button>
                </div>
              </template>
              <el-table v-loading="loading" :data="sendList">
                <el-table-column label="发货单位" align="center" prop="contactsName" />
                <el-table-column
                  label="信用代码/身份证"
                  align="center"
                  prop="contactsUscc"
                />
                <el-table-column label="联系人" align="center" prop="contacts" />
                <el-table-column label="联系电话" align="center" prop="contactsPhone" />
                <el-table-column label="所在城市" align="center" prop="contactsAddr" />
                <el-table-column label="详细地址" align="center" prop="contactsDetailAddr" />
                <el-table-column label="操作" align="center">
                  <template #default="scope">
                    <el-button link type="primary" @click="editContacts(scope)">编辑</el-button>
                    <el-button link type="danger" @click="handleDelete('0', scope)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
            <el-card :class="[prefixCls, 'mb-15px']" shadow="never" id="target4">
              <template #header>
                <div class="box-card">
                  <span style="font-weight: 700; font-size: 16px;">收货人(非必填项)</span>
                  <el-button type="primary" @click="openContacts(1)" style="float: right">新增</el-button>
                </div>
              </template>
              <el-table v-loading="loading" :data="receiptList">
                <el-table-column label="发货单位" align="center" prop="contactsName" />
                <el-table-column
                  label="信用代码或个人证件号"
                  align="center"
                  prop="contactsUscc"
                />
                <el-table-column label="联系人" align="center" prop="contacts" />
                <el-table-column label="联系电话" align="center" prop="contactsPhone" />
                <el-table-column label="所在城市" align="center" prop="contactsAddr" />
                <el-table-column label="详细地址" align="center" prop="contactsDetailAddr" />
                <el-table-column label="操作" align="center">
                  <template #default="scope">
                    <el-button link type="primary" @click="editContacts(scope)">编辑</el-button>
                    <el-button link type="danger" @click="handleDelete('1', scope)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-col>
        <el-col :span="2">
          <el-affix :offset="60">
            <el-anchor :container="containerRef"
                       direction="vertical" :offset="30" type="underline"  @click="handleClick">
              <el-anchor-link href="#target1">
                基本信息
              </el-anchor-link>
              <el-anchor-link href="#target2">
                结算信息
              </el-anchor-link>
              <el-anchor-link href="#target5">
                银行账户
              </el-anchor-link>
              <el-anchor-link href="#target3">
                发货人
              </el-anchor-link>
              <el-anchor-link href="#target4">
                收货人
              </el-anchor-link>
            </el-anchor>
          </el-affix>
        </el-col>
      </el-row>
      <el-form-item style="float: right">
        <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="close">返 回</el-button>
      </el-form-item>
    </el-form>
    <!-- 联系人 -->
    <el-dialog v-model="contactDialogVisible" title="新增发货人" width="50%" center>
      <el-form
        ref="contactsFormRef"
        :model="contactsFormData"
        :rules="contactsFormRules"
        label-width="240px"
        v-loading="formLoading"
        class="demo-form-inline"
      >
        <el-form-item label="单位全称" prop="contactsName">
          <el-input v-model="contactsFormData.contactsName" placeholder="请输入单位全称" />
        </el-form-item>
        <el-form-item label="信用代码/身份证" prop="contactsUscc">
          <el-input
            v-model="contactsFormData.contactsUscc"
            placeholder="请输入统一社会信用代码或个人证件号"
          />
        </el-form-item>
        <el-form-item label="法人" prop="legalPerson">
          <el-input v-model="contactsFormData.legalPerson" placeholder="请输入法人" />
        </el-form-item>
        <el-form-item label="法人身份证" prop="legalIdCardNo">
          <el-input v-model="contactsFormData.legalIdCardNo" placeholder="请输入法人身份证" />
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="contactsFormData.contacts" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactsPhone">
          <el-input v-model="contactsFormData.contactsPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="所在城市" prop="contactsAddrOptions">
          <el-cascader
            :options="cityOptions"
            v-model="contactsFormData.contactsAddrOptions"
            @change="handleChange"
            filterable
            clearable
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="contactsDetailAddr">
          <el-input v-model="contactsFormData.contactsDetailAddr" placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="contactDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleContactlick">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 银行信息 -->
    <el-dialog v-model="bankDialogVisible" title="新增银行信息" width="50%">
      <el-form
        ref="bankFormRef"
        :model="customerBankData"
        :rules="customerBankRules"
        label-width="240px"
        v-loading="formLoading"
        class="demo-form-inline"
      >
        <el-form-item label="收款人" prop="payeeName">
          <el-input v-model="customerBankData.payeeName" placeholder="请输入收款人" />
        </el-form-item>
<!--        <el-form-item label="开户银行编码" prop="bankCode">-->
<!--          <el-input v-model="customerBankData.bankCode" placeholder="请输入开户银行编码" />-->
<!--        </el-form-item>-->
        <el-form-item label="开户银行" prop="bankCode">
          <el-select
            v-model="customerBankData.bankCode"
            placeholder="请选择开户银行"
            style="width: 200px"
            @change="bankChange"
          >
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.BANK)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开户支行" prop="bankBranchName">
          <el-input v-model="customerBankData.bankBranchName" placeholder="请输入开户支行" />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankAccountNo">
          <el-input v-model="customerBankData.bankAccountNo" placeholder="请输入银行账号" />
        </el-form-item>
        <el-form-item label="开户名/开户单位" prop="bankAccountName">
          <el-input v-model="customerBankData.bankAccountName" placeholder="请输入开户名/开户单位" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bankDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleBanklick">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </ContentWrap>
</template>
<script setup lang="ts">
import { CustomerApi, CustomerVO} from '@/api/base/customer'
import { CustomerContactApi } from '@/api/base/customercontact'
import { CustomerBankApi } from '@/api/base/customerbank'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { regionData, codeToText } from 'element-china-area-data'
import { useTagsViewStore } from '@/store/modules/tagsView'
import {useDesign} from "@/hooks/web/useDesign";
const cityOptions = ref(regionData)
const loading = ref(false)
const { t } = useI18n() // 国际化
const { query } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由
const message = useMessage() // 消息弹窗
const contactDialogVisible = ref(false) //联系人弹窗
const bankDialogVisible = ref(false) //银行卡弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
// const dialogTitle = ref('') // 弹窗的标题
const { getPrefixCls } = useDesign()

const prefixCls = getPrefixCls('content-wrap')
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const contactsFormType = ref('')
const bankFormType = ref('')
let qid: any = undefined
const formData = ref({
  id: undefined,
  hasCreate: false,
  customerNo: undefined,
  customerType: undefined,
  customerName: undefined,
  shortName: undefined,
  customerUscc: undefined,
  legalPerson: undefined,
  legalIdCardNo: undefined,
  busiScope: undefined,
  contacts: undefined,
  contactsPhone: undefined,
  fixedPhone: undefined,
  customerAddrCode: undefined,
  customerAddr: undefined,
  customerAddrDetail: undefined,
  registerAddr: undefined,
  receiveAddr: undefined,
  paymentMethod: undefined,
  settlementType: undefined,
  settlementWays: undefined,
  settlementDays: undefined,
  receiptType: undefined,
  contactsAddrOptions: undefined,
  consignorDetailAddr: undefined
})
const formRules = reactive({
  customerName: [{ required: true, message: '单位全称不能为空', trigger: 'blur' }],
  customerUscc: [{ required: true, message: '统一社会信用代码不能为空', trigger: 'blur' }],
  legalPerson: [{ required: true, message: '法人不能为空', trigger: 'blur' }],
  legalIdCardNo: [{ required: true, message: '法人身份证不能为空', trigger: 'blur' }],
  rate: [{ required: true, message: '费率不能为空', trigger: 'blur' }],
  contactsPhone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
  contacts: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  contactsAddrOptions: [{ required: true, message: '所在城市不能为空', trigger: 'blur' }],
  consignorDetailAddr: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
  customerNo: [{ required: true, message: '单位编号不能为空', trigger: 'blur' }],
  shortName: [{ required: true, message: '单位简称不能为空', trigger: 'blur' }],
  settlementWays: [{ required: true, message: '结算方式不能为空', trigger: 'blur' }],
  settlementType: [{ required: true, message: '结算类型不能为空', trigger: 'blur' }],
  paymentMethod: [{ required: true, message: '付款方式不能为空', trigger: 'blur' }],
  receiptType: [{ required: true, message: '回单类型不能为空', trigger: 'blur' }],
  taxesNo: [{ required: true, message: '纳税人识别号不能为空', trigger: 'blur' }],
  accountName: [{ required: true, message: '开户行/开户单位不能为空', trigger: 'blur' }],
  telephone: [{ required: true, message: '固定电话不能为空', trigger: 'blur' }],
  bankCode: [{ required: true, message: '开户行不能为空', trigger: 'blur' }],
  registerAddr: [{ required: true, message: '注册地址不能为空', trigger: 'blur' }],
  bankBranchName: [{ required: true, message: '开户分行不能为空', trigger: 'blur' }],
  receiveAddr: [{ required: true, message: '收件地址不能为空', trigger: 'blur' }],
  accountNo: [{ required: true, message: '开户账号不能为空', trigger: 'blur' }]
})

const contactsFormData = ref({
  index: 0,
  id: undefined,
  customerId: qid,
  contactsType: undefined,
  contactsName: undefined,
  contactsUscc: undefined,
  legalPerson: undefined,
  legalIdCardNo: undefined,
  contacts: undefined,
  contactsPhone: undefined,
  contactsAddrCode: undefined,
  contactsAddr: undefined,
  contactsDetailAddr: undefined,
  contactsAddrOptions: []
})

/** 重置表单 */
const resetContactsForm = () => {
  contactsFormData.value = {
    id: undefined,
    customerId: qid,
    contactsType: undefined,
    contactsName: undefined,
    contactsUscc: undefined,
    legalPerson: undefined,
    legalIdCardNo: undefined,
    contacts: undefined,
    contactsPhone: undefined,
    contactsAddrCode: undefined,
    contactsAddr: undefined,
    contactsDetailAddr: undefined,
    contactsAddrOptions: []
  }
  contactsFormRef.value?.resetFields()
}

const customerBankData = ref({
  id: undefined,
  customerUscc: undefined,
  payeeName: undefined,
  bankCode: undefined,
  bankName: undefined,
  bankBranchName: undefined,
  bankAccountNo: undefined,
  bankAccountName: undefined,
  fixedPhone: undefined,
  registerAddr: undefined,
  receiveAddr: undefined,
  hasDefault: 0
})

/** 重置表单 */
const resetCustomerBankForm = () => {
  customerBankData.value = {
    id: undefined,
    customerUscc: undefined,
    payeeName: undefined,
    bankCode: undefined,
    bankName: undefined,
    bankBranchName: undefined,
    bankAccountNo: undefined,
    bankAccountName: undefined,
    fixedPhone: undefined,
    registerAddr: undefined,
    receiveAddr: undefined,
    hasDefault: 0
  }
  bankFormRef.value?.resetFields()
}

const contactsFormRules = reactive({
  contactsName: [{ required: true, message: '单位全称不能为空', trigger: 'blur' }],
  // contactsCode: [
  //   { required: true, message: '统一社会信用代码或个人证件号不能为空', trigger: 'blur' }
  // ],
  contacts: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  contactsPhone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
  contactsAddrOptions: [{ required: true, message: '所在城市不能为空', trigger: 'blur' }],
  contactsDetailAddr: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }]
})

const customerBankRules = reactive({

})

const formRef = ref() // 表单 Ref
const contactsFormRef = ref()
const bankFormRef = ref()
const sendList = ref([]) // 发货列表的数据
const receiptList = ref([]) // 发货列表的数据
const bankList = ref([])

/** 打开弹窗 */
const init = async () => {
  let id = query.id as unknown as number
  if (id != undefined) {
    qid = id
  }
  formType.value = query.type
  resetForm()
  // 修改时，设置数据
  //初始化数据
  formData.value.settlementWays = 1
  formData.value.settlementType = 1
  formData.value.paymentMethod = 9
  formData.value.receiptType = 0
  if (id != 'undefined') {
    formLoading.value = true
    try {
      formData.value = await CustomerApi.getCustomer(id)
      let params = {
        customerUscc: formData.value.customerUscc
      }
      const list = await CustomerContactApi.getCustomerContactList(params);
      sendList.value = list.filter((item) => item.contactsType == 0)
      receiptList.value = list.filter((item) => item.contactsType == 1)
      formData.value.contactsAddrOptions = formData.value.customerAddrCode.split('-')
      formData.value.settlementWays = parseInt(formData.value.settlementWays)
      formData.value.settlementType = parseInt(formData.value.settlementType)
      formData.value.paymentMethod = parseInt(formData.value.paymentMethod)
      formData.value.receiptType = parseInt(formData.value.receiptType)
      bankList.value = await CustomerBankApi.getCustomerBankList(params)
    } finally {
      formLoading.value = false
    }
  }
}

// const detailAddrChange = () => {
//   formData.value.registerAddr = formData.value.consignorDetailAddr
// }
// const registerAddrInput = () => {
//   formData.value.consignorDetailAddr = formData.value.registerAddr
// }
// const customNameInput = () => {
//   formData.value.accountName = formData.value.customerName
// }
//
// const accountNameInput = () => {
//   formData.value.customerName = formData.value.accountName
// }

const initContacts = async () => {
  const list = await CustomerContactApi.getCustomerContactList({
    customerUscc: query.customerUscc
  })
  sendList.value = list.filter((item) => item.contactsType == 0)
  receiptList.value = list.filter((item) => item.contactsType == 1)
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CustomerVO
    data.sendList = JSON.stringify(sendList.value)
    data.receiptList = JSON.stringify(receiptList.value)
    data.bankList = JSON.stringify(bankList.value)
    if (formType.value === 'create') {
      //判断是否有默认的账户
      const bankDef = bankList.value.find((item) => {
        return item.hasDefault == '1'
      })
      console.log('bankDef', bankDef == undefined)
      if(bankDef == undefined){
        message.error('请选择一条银行账户为默认账户')
        return
      }
      await CustomerApi.createCustomer(data)
      message.success(t('common.createSuccess'))
    } else {
      await CustomerApi.updateCustomer(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    close()
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    hasCreate: false,
    customerNo: undefined,
    customerType: undefined,
    customerName: undefined,
    shortName: undefined,
    rate: undefined,
    contacts: undefined,
    contactsPhone: undefined,
    customerAddrCode: undefined,
    customerAddr: undefined,
    consignorDeailAddr: undefined,
    taxesNo: undefined,
    telephone: undefined,
    registerAddr: undefined,
    receiveAddr: undefined,
    bankCode: undefined,
    bankName: undefined,
    bankBranchName: undefined,
    accountNo: undefined,
    accountName: undefined,
    settlementWays: undefined
  }
  formRef.value?.resetFields()
}

const openContacts = (contactsType: any) => {
  resetContactsForm()
  contactsFormType.value = 'create'
  contactsFormData.value.contactsType = contactsType
  contactDialogVisible.value = true
}

const editContacts = (scope: any) => {
  contactsFormData.value = Object.assign({}, scope.row)
  contactsFormData.value.index = scope.$index
  contactsFormType.value = 'update'
  contactsFormData.value.contactsAddrOptions = scope.row.contactsAddrCode.split('-')
  contactDialogVisible.value = true
}

const editBank = (scope: any) => {
  customerBankData.value = Object.assign({}, scope.row)
  customerBankData.value.index = scope.$index
  bankFormType.value = 'update'
  bankDialogVisible.value = true
}

const openBank = () => {
  resetCustomerBankForm()
  bankFormType.value = 'create'
  bankDialogVisible.value = true
}

const handleContactlick = async () => {
  // 校验表单
  if (!contactsFormRef.value) return
  const valid = await contactsFormRef.value.validate()
  if (!valid) return
  let data = Object.assign({}, contactsFormData.value)
  if (formType.value == 'create') {
    //刚创建的则新增 无需与后端交互
    if (contactsFormType.value == 'create') {
      if (data.contactsType == 0) {
        sendList.value.push(data)
      }
      if (data.contactsType == 1) {
        receiptList.value.push(data)
      }
    } else {
      if (data.contactsType == 0) {
        console.log('data.index', data.index)
        sendList.value.splice(data.index, 1, data)
      }
      if (data.contactsType == 1) {
        receiptList.value.splice(data.index, 1, data)
      }
    }
  } else {
    //如果是修改 则直接与后端交互
    if (contactsFormType.value == 'create') {
      contactsFormData.value.customerId = query.id
      await CustomerContactApi.createCustomerContact(contactsFormData.value)
    } else {
      await CustomerContactApi.updateCustomerContact(contactsFormData.value)
    }
    initContacts()
  }
  contactDialogVisible.value = false
}

const handleBanklick = async () => {
  try{
    // 校验表单
    if (!bankFormRef.value) return
    const valid = await bankFormRef.value.validate()
    if (!valid) return
    let data = Object.assign({}, customerBankData.value)
    if(formType.value == 'create'){
      if (bankFormType.value == 'create') {
        //刚创建的则新增 无需与后端交互
        bankList.value.push(data)
      } else {
        bankList.value.splice(data.index, 1, data)
      }
    }else{
      //如果是修改 则直接与后端交互
      if (bankFormType.value == 'create') {
        customerBankData.value.customerUscc = query.customerUscc
        await CustomerBankApi.createCustomerBank(customerBankData.value)
      } else {
        await CustomerBankApi.updateCustomerBank(customerBankData.value)
      }
      bankList.value = await CustomerBankApi.getCustomerBankList({
        customerUscc: query.customerUscc
      })
    }
  }catch (e) {

  }finally {
    bankDialogVisible.value = false
  }
}

const handleBaseChange = () => {
  var str = ''
  if (formData.value.contactsAddrOptions[0] != null) {
    str += codeToText[formData.value.contactsAddrOptions[0]] + '-'
  }
  if (formData.value.contactsAddrOptions[1] != null) {
    str += codeToText[formData.value.contactsAddrOptions[1]] + '-'
  }
  if (formData.value.contactsAddrOptions[2] != null) {
    str += codeToText[formData.value.contactsAddrOptions[2]] + '-'
  }
  formData.value.customerAddr = str.substring(0, str.length - 1)
  formData.value.customerAddrCode =
    formData.value.contactsAddrOptions[0] +
    '-' +
    formData.value.contactsAddrOptions[1] +
    '-' +
    formData.value.contactsAddrOptions[2]
}

const handleChange = () => {
  console.log(contactsFormData.value.contactsAddrOptions[0])
  var str = ''
  if (contactsFormData.value.contactsAddrOptions[0] != null) {
    str += codeToText[contactsFormData.value.contactsAddrOptions[0]] + '-'
  }
  if (contactsFormData.value.contactsAddrOptions[1] != null) {
    str += codeToText[contactsFormData.value.contactsAddrOptions[1]] + '-'
  }
  if (contactsFormData.value.contactsAddrOptions[2] != null) {
    str += codeToText[contactsFormData.value.contactsAddrOptions[2]] + '-'
  }
  contactsFormData.value.contactsAddr = str.substring(0, str.length - 1)
  contactsFormData.value.contactsAddrCode =
    contactsFormData.value.contactsAddrOptions[0] +
    '-' +
    contactsFormData.value.contactsAddrOptions[1] +
    '-' +
    contactsFormData.value.contactsAddrOptions[2]
}

const handleDelete = async (type: any, scope: any) => {
  if (formType.value == 'create') {
    if (type == '0') {
      sendList.value.splice(scope.$index, 1)
    }
    if (type == '1') {
      receiptList.value.splice(scope.$index, 1)
    }
  } else {
    await CustomerContactApi.deleteCustomerContact(scope.row.id)
    initContacts()
  }
}

const handleBankDelete = async (type: any, scope: any) => {
  if (formType.value == 'create') {
    bankList.value.splice(scope.$index, 1)
  } else {
    await CustomerBankApi.deleteCustomerBank(scope.row.id)
    bankList.value = await CustomerBankApi.getCustomerBankList({
      customerUscc: query.customerUscc
    })
  }
}

const bankChange = (bankCode: any) => {
  const bankData = getStrDictOptions(DICT_TYPE.BANK).find((item) => {
    return item.value == bankCode
  })
  customerBankData.value.bankName = bankData.label
}

const close = () => {
  delView(unref(currentRoute))
  push('/base/base-customer')
}

// const bankChange = (bank: any) => {
//   let obj = {}
//   obj = getStrDictOptions(DICT_TYPE.BANK).find((item) => {
//     return item.value === bank
//   })
//   formData.value.bankName = obj.label
// }

const containerRef = ref<HTMLElement | null>(null)
const handleClick = (e: MouseEvent) => {
  e.preventDefault()
}
const handleDefChange = (row: any) => {
  CustomerBankApi.updateDef({
    customerUscc: row.customerUscc,
    bankAccountNo: row.bankAccountNo
  })
}
init()
</script>
<style lang="scss" scoped>
.scroll-container{
  height: calc(100vh - var(--top-tool-height) - var(--tags-view-height) - var(--app-footer-height)) !important;
  overflow-y: auto;
  &::-webkit-scrollbar{
    width: 0;
    background-color: transparent;
  }
}
.row {
  height: 300px;
}
</style>
